package com.huishao.demo.controller;

import com.huishao.demo.entity.Email;

import com.huishao.demo.service.EmailService;
import com.huishao.demo.service.KeyService;
import com.huishao.demo.utils.PwdGenerate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.huishao.demo.common.EmailCommon.*;

/**
 * 这是一个开放给外界的特殊接口，如发送邮件，检测信息等，按时补上
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonInterfaceController {

    @Autowired
    EmailService mailService;

    @Resource
    KeyService keyService;


    /**
     * 此处为post方式进行发送邮件
     * @param m 携带必要参数的email实体
     * @return 返回结果
     */
    @PostMapping("/sendEmail")
    public Map<String,String> sendEmailPostFunctions(@RequestBody Email m) {
        Map<String, String> map = new HashMap<>();
        try {
            mailService.sendSimpleMail(MY_EMAIL,
                    TO_EMAIL,
                    CC,
                    m.getTitle(),
                    m.getContent());
        }catch (Exception e) {
            map.put("msg",EMAIL_SEND_ERROR);
            return map;
        }
        map.put("msg",EMAIL_SEND_SUCCES);
        return map;
    }
    /**
     * 此处为get方式进行发送邮件
     * @param title 携带必要参数的email实体
     * @param content 携带必要参数的email实体
     * @return 返回结果
     */
    @GetMapping("/sendEmail")
    public Map<String,String> sendEmailGetFunctions(@RequestParam String title, @RequestParam String content) {
        Map<String, String> map = new HashMap<>();
        try {
            mailService.sendSimpleMail(MY_EMAIL,
                    TO_EMAIL,
                    CC,
                    title,
                    content);
        }catch (Exception e) {
            map.put("msg",EMAIL_SEND_ERROR);
            return map;
        }
        map.put("msg",EMAIL_SEND_SUCCES);
        return map;
    }

    @GetMapping("sendKey")
    public void sendKey() throws Exception {
        String pwd = PwdGenerate.generate();
        mailService.sendKeyEmail(MY_EMAIL,
                TO_EMAIL,
                CC,
                KEY_SUBJECT,
                pwd
        );
        keyService.insertKey(PwdGenerate.encryption(pwd));
        log.info("key已发送！时间是 " + new Date());
    }

}
